package com.lemon.smartsafety.ui.activity.safe.inspection;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.view.SpacesItemDecoration;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.DataInfo;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.datacoll.BuildingCheckItemRefreshEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.inspection.InspectionCheckItemStepTwoFinishEvent;
import com.lemon.smartsafety.entity.safe.company.BindQrcodeEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingCheckItemVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingIndexVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingItemCountVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.entity.safe.inspection.CompanyBuildingItemCheckInfoVo;
import com.lemon.smartsafety.entity.safe.inspection.CompanyBuildingItemFlowVo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.InspectionServices;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.tag.BaseTAG;
import com.lemon.smartsafety.tag.DefaultCode;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.activity.safe.data.BuildingCheckItemBindNfcActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.ui.adapter.safe.inspection.CheckItemFlowAdapter;
import com.lemon.smartsafety.ui.fragment.safe.data.BuildingCheckItemListFragment;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafetynew.ui.activity.qrcode.CodeUtils;
import com.lemon.smartsafetynew.ui.activity.qrcode.QRcodeActivity;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.permission.EasyPermissions;

/**
 * Created by Cooliean on 16/4/4.
 * 安全巡查-检查项目详情界面
 */
public class SafeInspectionStepOneActivity extends PhotoSelectBaseActivity implements RecyclerTClickListener<CompanyBuildingItemFlowVo> {

    private LoggerHelper loggerHelper = new LoggerHelper(SafeInspectionStepOneActivity.class);


    @Bind(R.id.tv_tip)
    TextView     tvTip;
    @Bind(R.id.tv_remark)
    TextView     tvRemark;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.btn_submit)
    Button       btnSubmit;
    @Bind(R.id.btn_view_record)
    Button       btnViewRecord;

    @Bind(R.id.ll_evidence)
    LinearLayout llEvidence;


    /**
     * bundle info
     */
    private CompanyBuildingVo          mCompanyBuildingVo;
    private CompanyBuildingIndexVo     mCompanyBuildingIndexVo;
    private CompanyBuildingItemCountVo mCompanyBuildingItemCountVo;
    private CompanyBuildingCheckItemVo mCompanyBuildingCheckItemVo;

    private String                          sCheckId = "";
    private List<CompanyBuildingItemFlowVo> mFlows   = new ArrayList<>();

    private CheckItemFlowAdapter mAdapter;
    SpacesItemDecoration mItemDecoration;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mCompanyBuildingVo = (CompanyBuildingVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILD_INFO);
            mCompanyBuildingIndexVo = (CompanyBuildingIndexVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILDING_INDEX_VO);
            mCompanyBuildingItemCountVo = (CompanyBuildingItemCountVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILDING_ITEM_COUNT);
            mCompanyBuildingCheckItemVo = (CompanyBuildingCheckItemVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO);
        }
    }

    @Override
    protected void initTitle() {
        setBarTitle(R.string.safe_title);
    }

    @Override
    protected void callFinish() {
        IApplication._tempOneActivity = null;
        AppManager.getAppManager().finishActivity(SafeInspectionStepOneActivity.this);
        System.gc();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_inspection_step_one;
    }


    @Override
    protected void initViews() {
        super.initViews();
        if (null == mCompanyBuildingVo) {
            loggerHelper.w("mCompanyBuildingVo null");
        }
        if (null == mCompanyBuildingIndexVo) {
            loggerHelper.w("mCompanyBuildingIndexVo null");
        }

        if (null == mCompanyBuildingItemCountVo) {
            loggerHelper.w("mCompanyBuildingItemCountVo null");
        }
//        if (null == mCompanyBuildingVo || null == mCompanyBuildingIndexVo || null == mCompanyBuildingItemCountVo) {
//            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
//                @Override
//                public void onCall() {
//                    callFinish();
//                }
//            });
//            return;
//        }

        initViewValue();

        int spacingInPixels = recyclerView.getContext().getResources().getDimensionPixelSize(R.dimen.height_one_px);
        mItemDecoration = new SpacesItemDecoration(spacingInPixels);

        mAdapter = new CheckItemFlowAdapter(mFlows, this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);
        recyclerView.addItemDecoration(mItemDecoration);

        getNetData();

        IApplication._tempOneActivity = this;
    }

    private void initViewValue() {
        tvTip.setText(DataInfo.getPositionTitle(mCompanyBuildingVo, mCompanyBuildingIndexVo, mCompanyBuildingItemCountVo));
        tvRemark.setText(StringUtils.nullValue(mCompanyBuildingCheckItemVo.getRemark(), "无"));

        if (!StringUtils.getBoolean(mCompanyBuildingCheckItemVo.getIsPatrol())) {//不是巡更点就隐藏掉那个证据了。
            //setSelectEnable(false);
            llEvidence.setVisibility(View.GONE);
        }else{
            llEvidence.setVisibility(View.VISIBLE);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setIconEnable(menu, true);
        boolean menuResult = super.onCreateOptionsMenu(menu);
        //getMenuInflater().inflate(R.menu.menu_filter, menu);
        if (StringUtils.getBoolean(mCompanyBuildingCheckItemVo.getBindingQrcodeStatus())) {
            getMenuInflater().inflate(R.menu.menu_qrcode, menu);
        }
        if(StringUtils.getBoolean(mCompanyBuildingCheckItemVo.getBindingNfcStatus())) {
            getMenuInflater().inflate(R.menu.menu_nfc, menu);
        }
        return menuResult;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    /*    if (item.getItemId() == R.id.action_filter) {
            showPopWindow();
        }*/
        if (item.getItemId() == R.id.action_qrcode) {
            if (getOpenCameraEasyPermissions()) {
                startQrcode();
            }
        }
        if (item.getItemId() == R.id.action_nfc) {
            startNfc();
        }


        return super.onOptionsItemSelected(item);
    }

    private void startNfc() {
        Bundle bundle = new Bundle();
        bundle.putString(BaseTAG.COMMON_BASE_TAG, BuildingCheckItemListFragment.class.getName());
        UIHelper.showActivity(this, bundle, BuildingCheckItemBindNfcActivity.class);
    }


    private void startQrcode() {
        try {
            //Intent intent = new Intent(this, CaptureActivity.class);
            Intent intent = new Intent(this, QRcodeActivity.class);
            startActivityForResult(intent, DefaultCode.REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @return 不知为何 华为手机申请摄像头权限会崩溃
     */
    private boolean getOpenCameraEasyPermissions() {

        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            return true;
        } else {
            ToastUtil.show("请允许摄像头权限");
            return false;
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == DefaultCode.REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    LogUtils.LOGE("解析结果:" + result);
                    AppService.getBus().post(new BindQrcodeEvent(result, BuildingCheckItemListFragment.class.getName()));
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtils.toastMsg("解析二维码失败");
                }
            }
        }
    }
    @Override
    protected void initListener() {
        super.initListener();
    }


    @OnClick({R.id.btn_submit, R.id.btn_view_record})
    public void onclickAction(View view) {
        if (view.getId() == R.id.btn_submit) {
            if (!validateForm()) {
                return;
            }
            if (StringUtils.getBoolean(mCompanyBuildingCheckItemVo.getBindingNfcStatus())||StringUtils.getBoolean(mCompanyBuildingCheckItemVo.getBindingQrcodeStatus())) {
                mHUDUtil.showErrorTip("此点已绑定nfc或二维码");
                return;
            }
            getConfirmDialog("是否结束检查？", new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        doSubmitAction();
                    }
                }
            }).show();

        } else if (view.getId() == R.id.btn_view_record) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
            bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, mCompanyBuildingItemCountVo);
            bundle.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
            bundle.putSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO, mCompanyBuildingCheckItemVo);
            UIHelper.showActivity(this, bundle, SafeInspectionCheckItemRecordActivity.class);
        }
    }

    private void doSubmitAction() {
        final LemonRequestParams params = new LemonRequestParams();
        params.put("item_id", mCompanyBuildingCheckItemVo.getItemId());
        params.put("check_id", sCheckId);

        if (StringUtils.getBoolean(mCompanyBuildingCheckItemVo.getIsPatrol())) {//如果是巡更点
            getUploadItems(new SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>>() {
                @Override
                public void onStart() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mHUDUtil.showHUD();
                        }
                    });
                }

                @Override
                public void onFinish(List<UploadFileItem> data) {
                    if (data != null && data.size() != 0) {
                        params.put("files", mGson.toJson(data));
                    }
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            InspectionServices.init().saveInspectionCheck(params);
                        }
                    });
                }
            });
        } else {
            InspectionServices.init().saveInspectionCheck(params);
        }
    }

    /**
     * 是否需要维保
     *
     * @return
     */
    public boolean getGoRepair() {
        List<CompanyBuildingItemFlowVo> items  = mAdapter.getData();
        boolean                         result = false;
        if (null != items && items.size() != 0) {
            for (int i = 0; i < items.size(); i++) {
                String statusString = items.get(i).getStatus();
                if (DataInfo.RED_TAG.equals(statusString) || DataInfo.YELLOW_TAG.equals(statusString)) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }


    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        if (StringUtils.getBoolean(mCompanyBuildingCheckItemVo.getIsPatrol()) && !hasEvidence()) {
            mHUDUtil.showErrorTip("巡更点必须要采集材料证据");
            return false;
        }
        return true;
    }

    @Override
    public void evidencePlusEventHandler(String tag) {
        if (this.getClass().getName().equals(tag)) {
            showActionSheet(EvidenceActionSheetType.CAMERA_VOICE);
        }
    }


    private void getNetData() {
        sCheckId = StringUtils.nullValue(sCheckId);
        InspectionServices.init().getCheckItemFlowList(mCompanyBuildingCheckItemVo.getItemId(), sCheckId);
    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_INSPECTION_CHECK_ITEM_FLOW.equals(event.getTag())) {//获取检查流程数据
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.hidden();
                    setFlowList((CompanyBuildingItemCheckInfoVo) event.getObj());
                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }
        } else if (EventTag.TAG_INSPECTION_CHECK_ACTION.equals(event.getTag())) {//检查结束Action
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    //sCheckId != null && sCheckId.length() != 0 && getGoRepair()   这里跳转到上报维修哪里
                    mHUDUtil.showInfoTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            BuildingCheckItemRefreshEvent refreshEvent = new BuildingCheckItemRefreshEvent();
                            refreshEvent.setTag(BuildingCheckItemRefreshEvent.class.getName());
                            AppService.getBus().post(refreshEvent);
                            callFinish();

                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }
        }
    }


    private void setFlowList(CompanyBuildingItemCheckInfoVo vo) {
        if (vo != null && vo.getFlowList() != null && vo.getFlowList().size() != 0) {
            mFlows.clear();
            mFlows.addAll(vo.getFlowList());
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
        }

    }


    @Subscribe
    public void onEventMainThread(InspectionCheckItemStepTwoFinishEvent event) {
        sCheckId = StringUtils.nullValue(event.getData().getId());
        getNetData();
    }


    @Override
    public void onItemClick(CompanyBuildingItemFlowVo data, int position) {
        sCheckId = StringUtils.nullValue(sCheckId);
        Bundle bundle = new Bundle();
        bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, mCompanyBuildingItemCountVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO, mCompanyBuildingCheckItemVo);
        bundle.putSerializable(BundleKey.SAFE_INSPECTION_FLOW, data);
        bundle.putString(BundleKey.SAFE_INSPECTION_CHECK_ID, sCheckId);
        UIHelper.showActivity(this, bundle, SafeInspectionStepTwoActivity.class);
    }

    /****************************************************************************************************************
     * 保护现场
     ****************************************************************************************************************/
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        outState.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, mCompanyBuildingItemCountVo);
        outState.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
        outState.putSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO, mCompanyBuildingCheckItemVo);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mCompanyBuildingVo = (CompanyBuildingVo) savedInstanceState.getSerializable(BundleKey.COMPANY_BUILD_INFO);
            mCompanyBuildingIndexVo = (CompanyBuildingIndexVo) savedInstanceState.getSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO);
            mCompanyBuildingItemCountVo = (CompanyBuildingItemCountVo) savedInstanceState.getSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT);
            mCompanyBuildingCheckItemVo = (CompanyBuildingCheckItemVo) savedInstanceState.getSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(EventTag.TAG_INSPECTION_CHECK_ITEM_FLOW);
        mCompanyBuildingVo = null;
        mCompanyBuildingIndexVo = null;
        mCompanyBuildingItemCountVo = null;
        mCompanyBuildingCheckItemVo = null;
        IApplication._tempOneActivity = null;

        mHUDUtil.hidden();
    }

}
